package org.argetr.resim.proc;

import java.awt.image.DataBuffer;
import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;

import org.argetr.resim.proc.data.*;


public class ReScalePR extends IntensityTransformPR {
	public Data process() {
		PlanarImage i = getInputAsPlanarImage();
		ParameterBlock pbMaxMin = new ParameterBlock();
		pbMaxMin.addSource(i);
		RenderedOp extrema = JAI.create("extrema", pbMaxMin);
		double [] allMins = (double []) extrema.getProperty("minimum");
		double [] allMaxs = (double []) extrema.getProperty("maximum");
		// y = mx + n
		int nBand = ((ImageDA) getInput()).getNBands();
		double [] m = new double [nBand];
		double [] n = new double [nBand];
		for(int k = 0; k < nBand; k++){
			double max = allMaxs[k];
			double min = allMins[k];
			m[k] = 255.0 / (max - min);

			n[k] = - min * m[k];	
		}
		ParameterBlock pbRes = new ParameterBlock();
		pbRes.addSource(i);
		pbRes.add(m);
		pbRes.add(n);
		PlanarImage o = JAI.create("rescale", pbRes);
		ParameterBlock pbConvert = new ParameterBlock();
		pbConvert.addSource(o);
		pbConvert.add(DataBuffer.TYPE_BYTE);
		PlanarImage o2  = JAI.create("format", pbConvert);
		ImageDA out = new ImageDA(o2);
		setOutput((Data)out);	
		return getOutput();
	}
}
